package com.qf.android.sport.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SlidingPaneLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qf.android.sport.R;
import com.qf.android.sport.adapter.PopListAdapter;
import com.qf.android.sport.fragment.headline.HeadlineFragment;
import com.qf.android.sport.fragment.macth.AllMatchFragment;
import com.qf.android.sport.fragment.macth.MatchFragment;
import com.qf.android.sport.fragment.news.NewsFragment;
import com.qf.android.sport.layout.MyFrameLayout;
import com.qf.android.sport.layout.MySlidingPanelayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, SlidingPaneLayout.PanelSlideListener {

    private RadioGroup radioGroup;
    private FrameLayout topLayout;
    private NewsFragment newsFragment;
    private HeadlineFragment headlineFragment;
    private MatchFragment matchFragment;
    private RadioGroup topRadioGroup;
    private TextView textView;
    private TextView popupTitle;

    private RelativeLayout topRLayout;

    private PopupWindow popWindow;
    private ListView popList;
    private View view;
    private List<String> data;
    private PopListAdapter adapter;
    private MySlidingPanelayout slidingPaneLayout;
    private LinearLayout matchHeaderlayout;

    private RelativeLayout mainRlayout;
    private MyFrameLayout myFrameLayout;

    //两次点击返回键的时间间隔
    private long timeInterval = 2000;
    //第一次点击
    private long firstClick = -2000;
    private Toast mToast;
    private ImageView rotateIcon;
    private RotateAnimation mAnimation;
    private RotateAnimation mAnimation2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mToast = Toast.makeText(this, "再按一次退出体育头条", Toast.LENGTH_SHORT);
        myFrameLayout = (MyFrameLayout) findViewById(R.id.myFramelayout);
        mainRlayout = (RelativeLayout) findViewById(R.id.main_rLayout);
        topRLayout = (RelativeLayout) findViewById(R.id.topRLayout);
        radioGroup = (RadioGroup) findViewById(R.id.main_radioGroup);
        topLayout = (FrameLayout) findViewById(R.id.topLayout);
        slidingPaneLayout = (MySlidingPanelayout) findViewById(R.id.slidingPanel);
        slidingPaneLayout.setPanelSlideListener(this);
        slidingPaneLayout.setSliderFadeColor(Color.GRAY);
        radioGroup.setOnCheckedChangeListener(this);
        matchHeaderlayout = (LinearLayout) findViewById(R.id.LinearLayout_matchheader);
        initPopup();
        textView = (TextView) findViewById(R.id.news_title);
        initTopHeadline();
        initFragment();
    }
    //头条顶部 radiogroup
    private void initTopHeadline() {
        topRadioGroup = (RadioGroup) findViewById(R.id.topRadioGroup);
        topRadioGroup.setSelected(false);
        RadioButton button = (RadioButton) topRadioGroup.getChildAt(0);
        button.setChecked(true);
        topRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rtn1:
                        if (headlineFragment != null){
                            headlineFragment.getHeadlineViewPager().setCurrentItem(0);
                        }
                        topRadioGroup.setSelected(false);
                        break;
                    case R.id.rtn2:
                        if (headlineFragment != null){
                            headlineFragment.getHeadlineViewPager().setCurrentItem(1);
                        }
                        topRadioGroup.setSelected(true);
                        break;
                }
            }
        });
    }

    //初始化popupWindow，点击比赛界面标题时弹出
    private void initPopup() {
        initData();
        popupTitle = (TextView) findViewById(R.id.popupTitle);
        rotateIcon = (ImageView) findViewById(R.id.top_rotate_icon);
//        popupTitle.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showWindow(v);
//            }
//        });
        matchHeaderlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWindow(v);
                rotateIcon.startAnimation(getAnimation());
            }
        });

    }

    private RotateAnimation getAnimation(){
        if (mAnimation==null){
            mAnimation = new RotateAnimation(0,180,rotateIcon.getPivotX(),rotateIcon.getPivotY());
            mAnimation.setDuration(300);
            mAnimation.setFillAfter(true);
            mAnimation.setInterpolator(new LinearInterpolator());
        }
        return mAnimation;
    }

    private RotateAnimation getAnimation2(){
        if (mAnimation2==null){
            mAnimation2 = new RotateAnimation(180,0,rotateIcon.getPivotX(),rotateIcon.getPivotY());
            mAnimation2.setDuration(300);
            mAnimation2.setFillAfter(true);
            mAnimation2.setInterpolator(new LinearInterpolator());
        }
        return mAnimation2;
    }

    //初始化pop 中list的数据
    private void initData() {
        data = new ArrayList<>();
        data.add("热门赛事");
        data.add("全部");
        data.add("NBA");
        data.add("中国足球");
        data.add("国际足球");
        data.add("中国篮球");
    }

    private void showWindow(View v) {
        if (popWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.layout_popup, null);
            popList = (ListView) view.findViewById(R.id.popupList);
            adapter = new PopListAdapter(data, this, popupTitle.getText().toString());
            popList.setAdapter(adapter);
            popWindow = new PopupWindow(view, 150, 300);
        }
        popWindow.setFocusable(true);
        // 设置允许在外点击消失
        popWindow.setOutsideTouchable(true);
        int width = popupTitle.getWidth();
        int popWidth = dip2px(150);
        int xoff = (width - popWidth)/2;
        popWindow.showAsDropDown(popupTitle,xoff,0);
        popList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupTitle.setText(data.get(position));
                if (popWindow != null) {
                    popWindow.dismiss();
                    popWindow = null;
                }
                //根据position跳转不同的比赛界面
                FragmentManager manager = MainActivity.this.getSupportFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                AllMatchFragment allMatchFragment = new AllMatchFragment();
                Bundle args = new Bundle();

                switch (position) {
                    case 0://热门比赛
                        args.putString("match", "HotMatch");
                        allMatchFragment.setArguments(args);
                        break;
                    case 1://全部比赛
                        args.putString("match", "AllMatch");
                        allMatchFragment.setArguments(args);
                        break;
                    case 2://NBA
                        args.putString("match", "NBAMatch");
                        allMatchFragment.setArguments(args);
                        break;
                    case 3://中国足球
                        args.putString("match", "CFMatch");
                        allMatchFragment.setArguments(args);
                        break;
                    case 4://国际足球
                        args.putString("match", "IFMatch");
                        allMatchFragment.setArguments(args);
                        break;
                    case 5://中国篮球
                        args.putString("match", "CBMatch");
                        allMatchFragment.setArguments(args);
                        break;
                }
                transaction.replace(R.id.frameLayout_match_container_id, allMatchFragment);
                transaction.commit();
            }
        });
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                rotateIcon.startAnimation(getAnimation2());
            }
        });

    }

    private int dip2px(float dipValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private void initFragment() {
        FrameLayout frame = (FrameLayout) findViewById(R.id.frameLayout);
        newsFragment = new NewsFragment();
        headlineFragment = new HeadlineFragment();
        matchFragment = new MatchFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frameLayout, newsFragment);
        transaction.commit();
        RadioButton button = (RadioButton) radioGroup.getChildAt(0);
        button.setChecked(true);
    }
    //底部radioButton切换碎片及顶部布局显示变化
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        switch (checkedId) {


            case R.id.newsRtn:
                textView.setVisibility(View.VISIBLE);
                topRadioGroup.setVisibility(View.GONE);
                matchHeaderlayout.setVisibility(View.GONE);
                transaction.replace(R.id.frameLayout, newsFragment);
                break;
            case R.id.headlineRtn:
                textView.setVisibility(View.GONE);
                topRadioGroup.setVisibility(View.VISIBLE);
                matchHeaderlayout.setVisibility(View.GONE);
                transaction.replace(R.id.frameLayout, headlineFragment);
                break;
            case R.id.matchRtn:
                textView.setVisibility(View.GONE);
                topRadioGroup.setVisibility(View.GONE);
                matchHeaderlayout.setVisibility(View.VISIBLE);
                transaction.replace(R.id.frameLayout, matchFragment);
                break;
        }
        transaction.commit();
    }




    public void allClickEvent(View v) {
        switch (v.getId()) {
            case R.id.top_left_icon:
                if (!slidingPaneLayout.isOpen()){
                    slidingPaneLayout.openPane();
                }
                break;
        }

    }

    //slide监听
    @Override
    public void onPanelSlide(View panel, float slideOffset) {
        //滑动过程中主布局背景渐渐变灰
        slideOffset = (float) (1- 0.3 * slideOffset);
        int rgb = Color.rgb((int) (0xff * slideOffset), (int) (0xff * slideOffset), (int) (0xff * slideOffset));
        mainRlayout.setBackgroundColor(rgb);
    }

    @Override
    public void onPanelOpened(final View panel) {
        myFrameLayout.isIntercept(true);
        myFrameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                slidingPaneLayout.closePane();
            }
        });
    }

    @Override
    public void onPanelClosed(View panel) {
        myFrameLayout.isIntercept(false);
    }

    @Override
    public void onBackPressed() {
        if (slidingPaneLayout.isOpen()){
            slidingPaneLayout.closePane();
        }else if(System.currentTimeMillis()-firstClick > timeInterval){
            firstClick = System.currentTimeMillis();
            mToast.show();
        }else {
//            super.onBackPressed();
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        mToast.cancel();
        super.onDestroy();
    }

    public RadioGroup getTopRadioGroup() {
        return topRadioGroup;
    }
}
